import subprocess
import random
import string
import logging
import paramiko

logger = logging.getLogger(__name__)


def ping_host(ip_address, count=3, timeout=2):
    """
    检测主机是否可ping通
    """
    try:
        # 根据操作系统适配ping命令
        if subprocess.call(['ping', '-c', str(count), '-W', str(timeout), ip_address],
                           stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0:
            return True
        return False
    except Exception as e:
        logger.error(f"Ping {ip_address} 失败: {str(e)}")
        return False


def generate_password(length=16):
    """
    生成随机密码
    """
    chars = string.ascii_letters + string.digits + "!@#$%^&*()"
    return ''.join(random.choice(chars) for _ in range(length))


def change_linux_password(host, new_password):
    """
    远程修改Linux主机的root密码
    """
    try:
        # 创建SSH客户端
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # 连接到远程主机
        client.connect(
            host.ip_address,
            port=host.ssh_port,
            username='root',
            password=host.root_password,
            timeout=10
        )

        # 执行密码修改命令
        stdin, stdout, stderr = client.exec_command(f"echo 'root:{new_password}' | chpasswd")

        # 检查命令是否成功执行
        exit_status = stdout.channel.recv_exit_status()
        if exit_status != 0:
            error = stderr.read().decode('utf-8')
            logger.error(f"修改主机 {host.hostname} 密码失败: {error}")
            return False

        return True
    except Exception as e:
        logger.error(f"修改主机 {host.hostname} 密码时出错: {str(e)}")
        return False
    finally:
        if 'client' in locals() and client:
            client.close()